import { getToken, setToken, removeToken } from '@/utils/auth'
import { postLogin,getInfo } from '@/api/common'
// 用户信息
const state = {
  token: getToken(),
  name: '',
  avatar: require('@/assets/images/users.jpg'),
}
const mutations = {
  SET_NAME: (state, name) => {
      state.name = name
  },
  SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
}
const actions = {
  // 登录
  Login({ commit }, userInfo) {
    const userName = userInfo.userName.trim()
    const password = userInfo.password
    const imgCode = userInfo.imgCode
    return new Promise((resolve, reject) => {
      postLogin({userName, password,imgCode}).then(res => {
        setToken(res.token)
        commit('SET_TOKEN', res.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 获取用户信息
  GetInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      
      getInfo().then(res => {
        const user = res
        const avatar = user.userPic || require("@/assets/images/users.jpg")
        commit('SET_NAME', user.userName)
        commit('SET_AVATAR', avatar)
        resolve(res)
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 退出系统
  LogOut({ commit, state }) {
    return new Promise((resolve, reject) => {
      // logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      // }).catch(error => {
      //   reject(error)
      // })
    })
  },
}
export default {
    namespaced: true,
    state,
    mutations,
    actions
}